package arr;

import java.util.Arrays;

/**
 * @author yyz
 * @create 2023-11-25 14:30
 */
public class 将数组内两个区间内的有序元素合并 {
    private static void merge(int i, int iEnd, int j, int jEnd, int[] n1, int[] n2) {
        int k = 0;
        while (i <= iEnd && j <= jEnd) {
            if (n1[i] < n1[j]) {
                n2[k] = n1[i];
                k++;
                i++;
            } else {
                n2[k] = n1[j];
                k++;
                j++;
            }
        }
        if (i > iEnd) {
            System.arraycopy(n1, j, n2, k, jEnd - j + 1);
        }
        if (j > jEnd) {
            System.arraycopy(n1, i, n2, k, iEnd - i + 1);
        }
    }

    private static void merge(int i, int iEnd, int j, int jEnd, int k, int[] n1, int[] n2) {
        if (i > iEnd) {
            System.arraycopy(n1, j, n2, k, jEnd - j + 1);
            return;
        }
        if (j > jEnd) {
            System.arraycopy(n1, i, n2, k, iEnd - i + 1);
            return;
        }
        if (n1[i] < n1[j]) {
            n2[k] = n1[i];
            merge(i + 1, iEnd, j, jEnd, k + 1, n1, n2);
        } else {
            n2[k] = n1[j];
            merge(i, iEnd, j + 1, jEnd, k + 1, n1, n2);
        }
    }

    public static void main(String[] args) {
        int[] n1 = {1, 5, 6, 2, 4, 10, 11};
        int[] n2 = new int[n1.length];
//        merge(0, 2, 3, n1.length - 1, n1, n2);
        merge(0, 2, 3, n1.length - 1, 0, n1, n2);
        System.arraycopy(n2, 0, n1, 0, n2.length);
        System.out.println(Arrays.toString(n1));
    }
}
